<template>
    <div id="app">
      <h1>自律一下</h1>
      <input type="text" v-model="newTodoTitle" placeholder="添加新的待办事项">
      <input type="submit" value="添加" @click="addTodo">
      <div v-for="item in todos" :key="item.title">
        <todo-item :title="item.title" :completed="item.completed" @remove-todo="removeTodo" @update:completed="updateTodoCompleted"></todo-item>
      </div>
    </div>
  </template>
  
  <script>
  import TodoItem from './TodoItem.vue'
  
  export default {
    name: 'TodoList',
    components: {
      TodoItem
    },
    data() {
      return {
        todos: [],
        newTodoTitle: ''
      };
    },
    methods: {
      addTodo() {
        let flag = true;
        this.todos.forEach(todo => {
          if (todo.title === this.newTodoTitle) {
            flag = false;
          }
        });
        if (flag && this.newTodoTitle.trim() !== '') {
          const todo = {
            title: this.newTodoTitle,
            completed: false
          };
          this.todos.push(todo);
          this.newTodoTitle = ''; // Clear input after adding todo
        }
      },
      removeTodo(title) {
        this.todos = this.todos.filter(item => item.title !== title);
      },
      updateTodoCompleted(title) {
        this.todos.forEach(item => {
          if (item.title === title) {
            item.completed = !item.completed;
          }
        });
      }
    }
  }
  </script>
  
  <style scoped>
  
  </style>
  